package com.chinamsp.dydb.query.impl;

import java.sql.Date;
import java.text.ParseException;

import com.chinamsp.baisc.util.DateUtils;
import com.chinamsp.dydb.query.BaseValueConverter;
import com.chinamsp.dydb.query.FieldType;
import com.chinamsp.dydb.query.SymbolType;

/**
 * sql 值转换
 * @author shifenghu
 *
 */
public class SimpleValueConverter implements BaseValueConverter {

	private SimpleValueConverter() {}
	
	@Override
	public Object convert(String field, FieldType type, SymbolType exp, Object value) {
		if (value == null) {
			return value;
		}
		// 根据  expresion 处理
		switch(exp){
			case IS_NULL :
			case NOT_NULL:
				return null;
			case NOT_IN:
			case IN:
				// 检查是否是 集合类，如果不是则转换
				if (value instanceof String) {
					value = value.toString().split(",");
				}
				break;
			case LK:
				value = "%" + value.toString().trim()
						.replaceAll("_", "\\\\_")
						.replaceAll("%", "\\\\%") + "%";
				break;
			case LLK:
				value = "%" + value.toString().trim()
				.replaceAll("_", "\\\\_")
				.replaceAll("%", "\\\\%");
				break;
			case RLK:
				value = value.toString().trim()
				.replaceAll("_", "\\\\_")
				.replaceAll("%", "\\\\%") + "%" ;
				break;
			default:
				break;
		}
		
		// 根据 fieldType  + exp 处理
		switch (type) {
			case INT:
				value = value instanceof String ? Integer.valueOf(value.toString()) : value;
				break;
			case FLOAT:
				value = value instanceof String ? Float.valueOf(value.toString()) : value;
				break;
			case DATE:
				// 字符串
				if (value instanceof String) {
					try {
						value = DateUtils.parse(value.toString(), DateUtils.PATTERN_YYYY_MM_DD);
					} catch (ParseException e) {
						throw new IllegalArgumentException(e);
					}
				}
			case DATETIME:
				// 字符串
				if (value instanceof String) {
					try {
						value = DateUtils.parse(value.toString(), DateUtils.PATTERN_YYYY_MM_DD);
					} catch (ParseException e) {
						throw new IllegalArgumentException(e);
					}
				} else if (value instanceof Long) {
					value = new Date((Long) value);
				} else if (!(value instanceof Date)) {
					throw new IllegalArgumentException(String.format("[%s].[%s] 类型条件值格式错误[%s]", field, type, value));
				}
				break;
			default:
				break;
		}
		
		return value;
	}
	
	/**
	 * 单例
	 */
	public static final BaseValueConverter INSTANCE = new SimpleValueConverter();
}
